package com.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.provider.service.ResourceService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/provider")
public class ProviderSentinelController {
    /**
     * 限流:已完成
     * 拓展:通过一个设计限制此方法的访问时间?(例如12306的订票,只允许在指定时间订票)
     * 你的方案是什么? 基于springmvc中的拦截器 (15:10讲解)
     * @return
     */
    @GetMapping("/sentinel01")
    public String doSentinel01(){
        return "sentinel 01 test";
    }

    @GetMapping("/sentinel02")
    public String doSentinel02(){
        return "sentinel 02 test";
    }

    @Autowired
    private ResourceService resourceService;

    /**
     * 演示链路限流
     * @return
     */
    @GetMapping("/sentinel03")
    public String doSentinel03(){
       return resourceService.doGetResource();
       //return "sentinel 03 test";
    }

    //构建一个AtomicLong对象,提供了线程安全的自增,自减的操作
    private AtomicLong atomicLong=new AtomicLong(1);

    @GetMapping("/sentinel04")
    public  String doSentinel04() throws InterruptedException {
        long num = atomicLong.getAndIncrement();
        if(num%2==0){//模拟慢调用
            //........
            Thread.sleep(200);
            //throw new RuntimeException("timeout");
        }
        return "sentinel 04 test";
    }

    //http://localhost:8081/provider/sentinel/findById?id=10
    @GetMapping("/sentinel/findById")
    @SentinelResource("resource")
    public String doFindById(@RequestParam("id") Integer id){
        return "resource id is "+id;
    }

}
